<template>
  <div>
    <h1>学习进度</h1>
    <progress-bar :value="progress*100/8"></progress-bar>
    <h1>关卡列表</h1>
    <level-card v-for="level in levels" :key="level.id" :level="level" @unlock-next="handleUnlockNext"></level-card>
  </div>
</template>

<script>
import ProgressBar from '@/components/ProgressBar.vue';
import LevelCard from '@/components/LevelCard.vue';
import axios from 'axios';

export default {
  components: {
    ProgressBar,
    LevelCard,
  },
  data() {
    return {
      progress: 1,
      levels: [
        { id: 1, name: '关卡 1', description: '线性流程', unlocked: true },
        { id: 2, name: '关卡 2', description: '分支决策', unlocked: false },
        { id: 3, name: '关卡 3', description: '循环控制', unlocked: false },
        { id: 4, name: '关卡 4', description: '递归与分治', unlocked: false },
        { id: 5, name: '关卡 5', description: '回溯算法', unlocked: false },
        { id: 6, name: '关卡 6', description: '动态规划', unlocked: false },
        { id: 7, name: '关卡 7', description: '贪心算法', unlocked: false },
        { id: 8, name: '关卡 8', description: '综合应用', unlocked: false },
      ]
    };
  },
  async created() {
    await this.fetchProgress();
  },
  methods: {
    async fetchProgress() {
      const token = localStorage.getItem('token');
      if (!token) return;
      try {
        const response = await axios.get('http://localhost:3000/progress', {
          headers: { Authorization: token }
        });
        this.progress = response.data.progress;
        this.updateLevels();
      } catch (error) {
        console.error('获取进度失败:', error);
      }
    },
    updateLevels() {
      this.levels.forEach(level => {
        level.unlocked = level.id <= this.progress;
      });
    },
    handleUnlockNext(nextLevelId) {
      const nextLevel = this.levels.find(level => level.id === nextLevelId);
      if (nextLevel && nextLevel.id <= this.progress) {
        nextLevel.unlocked = true;
      }
    }
  }
};
</script>